package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.omg.CORBA.CTX_RESTRICT_SCOPE;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import reactor.util.function.Tuple3;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器类型,pre,routing,post,error
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;//设置前置过滤器
    }
    //设置过滤器的顺序号
    //在默认的第5个过滤器中,放入了访问的serviceId,
    @Override
    public int filterOrder() {
        return 6;
    }
    /**针对当前请求是否执行,过滤代码*/
    @Override
    public boolean shouldFilter() {
        //调用item-service 需要判断权限
        //否则,不判断权限,直接跳过过滤代码

        //过滤请求上下文对象
        RequestContext ctx= RequestContext.getCurrentContext();
        //从上下文对象获得调用的服务id
        String serviceId=
                (String)ctx.get(FilterConstants.SERVICE_ID_KEY);
        //如果服务id是item-service,返回true,否则返回false
        return "item-service".equalsIgnoreCase(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //http;//localhost:3001/item-service/u4y544yy45?token=uyt343t3
        //获取请求上下文对象
        RequestContext ctx=RequestContext.getCurrentContext();
        //从上下文获得request对象
        HttpServletRequest request=ctx.getRequest();
        //从request取出token参数
        String token=request.getParameter("token");
        //如果没有token,null,"","  "
        if(StringUtils.isBlank(token)){
            //阻止继续调用
            ctx.setSendZuulResponse(false);//发送
            //直接向客户端返回响应
            String json= JsonResult.build().code(400).msg("未存录!")
                    .toString();
            ctx.addZuulResponseHeader(
                    "context-Type","application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        return null;//当前zuul版本中这个返回值不起任何作用

    }
}

